<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ajax 实现搜索提示</title>
</head>
<body>
    <input type="search" name="" id="search">
    <ul id="result"></ul>

    <script type="module">
        import {getjson} from '../0.ajax/main.js';

        const searchInput = document.getElementById('search');
        const resultList = document.getElementById('result');

        const url = 'https://www.imooc.com/api/http/search/suggest?words=';

        const handleInputEvent = ()=>{
            if(searchInput.value.trim() !== ''){
                getjson(`${url}${searchInput.value}`).then(response =>{
                    console.log(response);

                    let html = '';
                    for(let item of response.data){
                        html += `<li>${item.word}</li>`;
                    }
                    resultList.style.display = '';
                    resultList.innerHTML = html;
                }).catch(err =>{
                    console.log(err);
                })
            }else{
                resultList.innerHTML = '';
                resultList.style.display = 'none';
            }
        }

        let timer = 0;  // 定时器

        searchInput.addEventListener('input',()=>{
            // handleInputEvent();
            if(timer){
                clearTimeout(timer);
            }
            timer = setTimeout(handleInputEvent,300);
        })
    </script>    
</body>
</html>